import util from '@ohos.util';
export  class BLEDataReceiver {
  // 协议常量
  private static readonly PROTOCOL_HEADER = 0xAA55;
  private static readonly HEADER_SIZE = 4; // AA55(2字节) + 长度(2字节)
  // 接收状态
  private buffer: Uint8Array | null = null;
  private expectedLength: number = 0;
  private receivedLength: number = 0;
  private isReceiving: boolean = false;

  /*
  * 处理接收到的数据分片
  * @param chunk 接收到的数据分片
  * @returns 完整数据包或null(如果还未接收完成)
  */
  handleChunk(chunk: ArrayBuffer): string | null {
    const chunkView = new Uint8Array(chunk);

    // 1. 检查是否是数据包开头
    if (!this.isReceiving && chunkView.length >= 4) {
      const headerView = new DataView(chunk.slice(0, 4));
      const header = headerView.getUint16(0, false);

      if (header === BLEDataReceiver.PROTOCOL_HEADER) {
        // 开始新数据包接收
        this.expectedLength = headerView.getUint16(2, false);
        this.buffer = new Uint8Array(this.expectedLength);
        this.receivedLength = 0;
        this.isReceiving = true;

        // 处理第一个分片中的数据
        const dataStart = Math.min(BLEDataReceiver.HEADER_SIZE, chunkView.length);
        const dataPart = chunkView.slice(dataStart);
        this.buffer.set(dataPart, 0);
        this.receivedLength += dataPart.length;

        return this.checkCompletion();
      }
    }

    // 2. 继续接收数据包
    if (this.isReceiving && this.buffer) {
      const remaining = this.expectedLength - this.receivedLength;
      const copyLength = Math.min(remaining, chunkView.length);

      this.buffer.set(chunkView.slice(0, copyLength), this.receivedLength);
      this.receivedLength += copyLength;

      return this.checkCompletion();
    }

    return null;
  }

  /*
  * 检查是否接收完成
  * @returns 完整JSON字符串或null
  */
  private checkCompletion(): string | null {
    if (this.receivedLength === this.expectedLength) {
      try {
        const jsonString = new util.TextDecoder().decode(this.buffer!);
        this.reset();
        return jsonString;
      } catch (e) {
        console.error('JSON解码失败:', e);
        this.reset();
        return null;
      }
    }
    return null;
  }

  /*
  * 重置接收状态
  */
  private reset() {
    this.buffer = null;
    this.expectedLength = 0;
    this.receivedLength = 0;
    this.isReceiving = false;
  }
}